require 'iplayer'
require 'thread'

include IPlayer
include IPlayer::Errors

class IPlayerDownload < NSObject
  
  attr_accessor :movie_name
  attr_accessor :progress
  attr_accessor :time_left

  kvc_accessor :movie_name
  kvc_accessor :progress
  kvc_accessor :time_left
  
  def init
    if super_init
      @http       = Net::HTTP
      @browser    = Browser.new(@http)
      @progress   = 0
      @movie_name = ""
      @time_left  = ""      
      return self
    end
  end
  
  def start_download(pid)
    @pid = pid
	  self.movie_name = "Querying BBC for info... [#{@pid}]"
    Thread.start {
      downloader = Downloader.new(@browser, @pid)
      begin
        available_versions = downloader.available_versions
        raise MP4Unavailable if available_versions.empty?
      
        # TODO: support version type preferences
        #version = available_versions.sort_by{ |v| 
        #  OPTIONS[:type_preference].index(v.name) || 100 
        #}.first
        version = available_versions.first
        title = Metadata.new(pid, @browser).full_title
      
        self.movie_name = "#{ title }.mov".gsub(/[^a-z0-9 \-\.]+/i, '')
        NSLog(@movie_name)
      
        # TODO: Specify download path
        #path = File.expand_path( File.join( OPTIONS[:download_path], filename ))
        path = File.expand_path( File.join( "~/Desktop", @movie_name ))
        NSLog("Saving #{path}")

        old_percentage = 0.0

        if File.exist?(path)
          offset = File.size(path)
          NSLog("Resuming download at #{offset} bytes.")
        else
          offset = 0
        end

        t_start = Time.new
        File.open(path, 'a+b') do |io|
          downloader.download(version.pid, io, offset) do |position, max|
            percentage = (position.to_f / max.to_f) * 100.0
            if percentage - old_percentage >= 0.1
              old_percentage = percentage
              self.progress = old_percentage;
            
              now = Time.new
              t_elapsed = now - t_start
              t_left = (t_elapsed / percentage * (100 - percentage))
              mins_left = (t_left / 60).to_i
              mins_label = mins_left == 1 ? "minute" : "minutes"
              self.time_left = "#{mins_left} #{mins_label}"
            end
          end
        end
        self.time_left = "Complete"
        
      rescue ParsingError    
        NSLog(
          "Unable to parse the programme page. Possible reasons:",
          "1. The iPlayer has changed", 
          "2. You are outside the UK (and not using a UK proxy)."
        )
      rescue FileUnavailable
        NSLog("An MP4 URL was found, but the download failed.")
      rescue MP4Unavailable
        NSLog("This programme is not currently available in an MP4 version.")
      end
    }
  
  end
end
